<template>
  <div class="p-2">
    <el-card>
      <template #header>
        <el-row
          :gutter="10"
          justify="space-between"
          align="middle"
        >
          <el-col :span="1.5">
            {{merchantName}}产品配置
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="primary"
              @click="handleAdd"
            >添加服务商</el-button>
          </el-col>
        </el-row>
      </template>
      <el-tabs
        v-model="queryParams.busType"
        @tab-click="tabClick"
      >
        <el-tab-pane
          v-for="item in tabList"
          :name="item"
        >
          <template #label>
            <dict-tag
              :options="wxfe_bus_type"
              :value="item"
            />
          </template>

          <el-table
            v-loading="loading"
            :data="productList"
            border
            ref="tableRef"
            max-height="calc(100vh - 342px)"
            :row-key="getRowKey"
            @select="getSelectFun"
            @select-all="handleSelectionAll"
          >
            <el-table-column
              type="selection"
              width="40"
              align="center"
              column-key="unId"
              :reserve-selection="true"
            />
            <el-table-column
              label="产品编号"
              align="center"
              min-width="160"
              prop="proNo"
            />
            <el-table-column
              label="服务商编号"
              align="center"
              min-width="160"
              prop="sydNo"
              :show-overflow-tooltip="true"
            />
            <el-table-column
              label="服务商名称"
              align="center"
              min-width="240"
              prop="serviceName"
              :show-overflow-tooltip="true"
              sortable
              class-name="serviceName"
            >
              <template #header>
                <div class="thHeader flex_jbetween_acenter">
                  <div class="left">
                    服务商名称
                  </div>
                  <el-popover
                    :visible="popoverVisible"
                    class="right"
                    placement="bottom-end"
                    trigger="click"
                    :width="200"
                  >
                    <template #reference>
                      <el-icon @click.stop.prevent="popoverVisible=!popoverVisible">
                        <ArrowDownBold />
                      </el-icon>
                    </template>
                    <div class="popover_box">
                      <div>
                        <el-input
                          v-model="serviceNameFilter"
                          placeholder="搜索服务商"
                        ></el-input>
                      </div>
                      <div class="flex_jbetween_acenter">
                        <el-button
                          icon="Search"
                          type="primary"
                          @click="filterTableData"
                        >确定</el-button>
                        <el-button @click="resetServiceNameFilter">重置</el-button>
                      </div>
                    </div>
                  </el-popover>
                </div>
              </template>
            </el-table-column>
            <el-table-column
              label="成本费率(%)"
              align="center"
              min-width="160"
              prop="costServiceCharge"
              sortable
            />
            <el-table-column
              label="配置服务费率(%)"
              align="center"
              min-width="160"
              prop="serviceCharge"
            >
              <template #default="scope">
                 <div :class="'input-with-validation '+scope.row.errorClass" >
                <el-input-number
                  v-model="scope.row.serviceCharge"
                  :precision="2"
                  :min="scope.row.costServiceCharge"
                  controls-position="right"
                   :disabled="scope.row.proStatus == 2 || !scope.row.proStatus"
                  style="width:100%;"
                />
                </div>
              </template>
            </el-table-column>
            <el-table-column
              label="计费模式"
              align="center"
              min-width="160"
              prop="chargeMode"
              sortable
            >
              <template #default="scope">
                <dict-tag
                  :options="charge_mode"
                  :value="scope.row.chargeMode"
                />
              </template>
            </el-table-column>
            <el-table-column
              label="到账方式"
              align="center"
              min-width="160"
              prop="settlementStyle"
              sortable
            >
              <template #default="scope">
                <dict-tag
                  :options="settlement_style"
                  :value="scope.row.settlementStyle"
                />
              </template>
            </el-table-column>
            <el-table-column
              label="单月发放上限（元）"
              align="center"
              min-width="170"
              prop="maxMonthStr"
              sortable
            />
            <el-table-column
              label="开票类型"
              align="center"
              min-width="160"
              prop="invoiceType"
            >
              <template #default="scope">
                <dict-tag
                  :options="invoice_type"
                  :value="scope.row.invoiceType"
                />
              </template>
            </el-table-column>
            <el-table-column
              label="开票项目"
              align="center"
              min-width="160"
              :show-overflow-tooltip="true"
              prop="invoiceItems"
            />
          </el-table>

          <pagination
            v-show="total > 0"
            :total="total"
            v-model:page="queryParams.pageNum"
            v-model:limit="queryParams.pageSize"
            @pagination="getList"
          />
        </el-tab-pane>
      </el-tabs>
      <div class="card-footer">
        <el-button @click="returnOn()">返回</el-button>
        <el-button
          type="primary"
          @click="saveSetting"
        >保存设置</el-button>
      </div>
    </el-card>
    <!-- 添加或修改服务商配置对话框 -->
    <el-dialog
      ref="formDialogRef"
      title="配置服务商"
      v-model="visible"
      width="600px"
      append-to-body
      @close="closeDialog"
    >
      <el-form
        :model="form"
        ref="userFormRef"
        label-width="auto"
        :rules="rules"
      >
        <el-row>
          <el-col :span="23">
            <el-form-item
              label="服务商"
              prop="sydId"
              required
            >
              <el-select
                v-model="form.sydId"
                placeholder="请选择服务商"
                style="width:100%"
                filterable
              >
                <el-option
                  v-for="(item,i) in salesmanList"
                  :label="item.service_name"
                  :value="item.syd_id"
                  :key="item.syd_id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel()">取 消</el-button>
          <el-button
            type="primary"
            @click="submitForm"
          >确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="productConfig" lang="ts">
import api from '@/api/enterprise/productConfiguration';
import {
  ProductQuery,
  ProductListVO,
  ServiceAgentForm,
  ServiceAgentVo,
  SaveServiceAgentForm,
  CheckLineObjVo
} from '@/api/enterprise/productConfiguration/types';
import { TabsPaneContext } from 'element-plus';
import { LocationQueryValue } from 'vue-router';
import { number } from 'vue-types';

const route = useRoute();
const router = useRouter();
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { wxfe_bus_type, invoice_type, charge_mode, settlement_style } = toRefs<any>(proxy?.useDict('wxfe_bus_type', 'invoice_type', 'charge_mode', 'settlement_style'));

const tabList = ref<Array<number | string>>([]);
const tableRef = ref<ElTableInstance[]>([]);
const productList = ref<ProductListVO[]>([]);
const oldProductList = ref<ProductListVO[]>([]);
const loading = ref(true);
const popoverVisible = ref(false);
const serviceNameFilter = ref<string>('');
const filterTableData = () => {
  productList.value = oldProductList.value.filter((data: ProductListVO) =>
    data.serviceName.toLowerCase().includes(serviceNameFilter.value.toLowerCase())
  );
};
const resetServiceNameFilter = () => {
  serviceNameFilter.value = '';
  popoverVisible.value = false;
  filterTableData();
};
const total = ref(0);
const merchantName = route.query.name as LocationQueryValue | LocationQueryValue[];
const queryParams = ref<ProductQuery>({
  merId: route.query.id,
  busType: '',
  pageNum: 1,
  pageSize: 10
});

/** 查询企业列表 */
const getSelBusType = async () => {
  loading.value = true;
  const res = await api.selBusType();
  tabList.value = res.data;
  tabList.value.forEach((e) => {
    checkLineObj.value[e] = [];
  });
  queryParams.value.busType = tabList.value.length ? tabList.value[0] : '';
  getList();
};
const tabClick = (pane: TabsPaneContext, ev: Event) => {
  if (pane.props.name == queryParams.value.busType) return;
  queryParams.value.busType = pane.props.name || '';
  getList();
};

/** 查询企业列表 */
const getList = async () => {
  loading.value = true;
  const res = await api.productList(queryParams.value);
  loading.value = false;
  productList.value = res.rows;
  if (tableRef.value.length && queryParams.value.busType) {
    checkLineObj.value[queryParams.value.busType] = [];
    let busType = typeof queryParams.value.busType == 'number' ? queryParams.value.busType : parseInt(queryParams.value.busType);
    tableRef.value[busType - 1].clearSelection();
  }
  productList.value.forEach((e: ProductListVO) => {
    e.costServiceCharge = e.costServiceCharge ? e.costServiceCharge : 0;
    if (e.proStatus == 1) {
      if (queryParams.value.busType) {
        checkLineObj.value[queryParams.value.busType].push(e);
      }
      if (tableRef.value.length && queryParams.value.busType) {
        let busType = typeof queryParams.value.busType == 'number' ? queryParams.value.busType : parseInt(queryParams.value.busType);
        tableRef.value[busType - 1].toggleRowSelection(e, true);
      }
    }
  });
  oldProductList.value = productList.value;
  total.value = res.total;
};

const getRowKey = (row: any) => {
  return row.unId;
};
let checkLineObj = ref<CheckLineObjVo>({});

const getSelectFun = (data: any, row: any) => {
  if (queryParams.value.busType) {
    // checkLineObj.value[queryParams.value.busType] = data;
    row.proStatus = row.proStatus == 1 ?2:1;

  }
};

const allSelect = ref([])
const allSelect1 = ref([])

// 多选事件
const handleSelectionAll = (objs: any) => {
  if (queryParams.value.busType) {
      if(objs.length > 0 ){
        allSelect.value = objs;
        allSelect.value.forEach(item=>{
            item.proStatus = 1;
        })
      }else{
        if(allSelect.value){
          allSelect.value.forEach(item=>{
              item.proStatus = 2;
          })
        }
      }
    // checkLineObj.value[queryParams.value.busType] = JSON.parse(JSON.stringify(objs));
    // console.log(checkLineObj.value, 'checkLineObj.value[queryParams.value.busType]');
  }

  // if (queryParams.value.busType) {
  //   checkLineObj.value[queryParams.value.busType] = JSON.parse(JSON.stringify(objs));
  //   console.log(checkLineObj.value[queryParams.value.busType], 'checkLineObj.value[queryParams.value.busType]');
  // }
};

// 返回
const returnOn = () => {
  proxy?.$router.go(-1);
  proxy?.$tab.closePage(route);
};
const saveSettingForm = ref<SaveServiceAgentForm>({
  boList: [
    {
      busType: '',
      chargeMode: '',
      costServiceCharge: '',
      invoiceItems: '',
      invoiceType: '',
      maxMonth: '',
      proNo: '',
      proStatus: '',
      serviceCharge: '',
      settlementStyle: ''
    }
  ],
  busType: '',
  merId: route.query.id,
  merNo: route.query.no
});
// 保存设置
const saveSetting = async () => {
  saveSettingForm.value.busType = queryParams.value.busType ? queryParams.value.busType : '';
  // for (let j = 0; j < productList.value.length; j++) {
  //   const el = productList.value[j];
  //   el.proStatus = 2;
  //   for (let i = 0; i < checkLineObj.value[saveSettingForm.value.busType].length; i++) {
  //     const e = checkLineObj.value[saveSettingForm.value.busType][i];
  //     if (el.unId == e.unId) {
  //       el.proStatus = 1;
  //       break;
  //     }
  //   }
  // }
  // for (let i = 0; i < productList.value.length; i++) {
  //   const e = productList.value[i];
  //   if (e.proStatus == 1 && !e.serviceCharge) return proxy?.$modal.msgError('请输入编号为' + e.proNo + '的配置服务费率！');
  // }
  let tag = true;
  for (let i = 0; i < productList.value.length; i++) {
    const e = productList.value[i];
    // if (e.proStatus == 1 && !e.serviceCharge) return proxy?.$modal.msgError('请输入编号为' + e.proNo + '的配置服务费率！');
    if (e.proStatus == 1 && !e.serviceCharge) {
      e.errorClass = 'error-message'
       proxy?.$modal.msgError('请为编号为' + e.proNo + '配置服务费率！')
      tag = false;
      break;
    }else{
      e.errorClass="";
    }
  }
  if(!tag){
    return;
  }

  saveSettingForm.value.boList = productList.value;
  console.log(saveSettingForm.value);
  let res = await api.merchantProduct(saveSettingForm.value);
  console.log(checkLineObj.value[saveSettingForm.value.busType], 'checkLineObj.value[saveSettingForm.value.busType]');
  proxy?.$modal.msgSuccess(res.msg);
  await getList();
};

/** 配置服务商 */
const visible = ref(false);
const salesmanList = ref<ServiceAgentVo[]>();
const form = ref<ServiceAgentForm>({
  merId: route.query.id,
  sydId: ''
});
const rules = {
  sydId: [{ required: true, message: '请选择服务商', trigger: 'blur' }]
};
const userFormRef = ref<ElFormInstance>();
const formDialogRef = ref<ElDialogInstance>();
/** 重置操作表单 */
const reset = () => {
  form.value = {
    merId: route.query.id,
    sydId: ''
  };
  userFormRef.value?.resetFields();
};

/** 取消按钮 */
const cancel = () => {
  visible.value = false;
  reset();
};
/** 配置服务商 */
const handleAdd = async (row: any) => {
  reset();
  visible.value = true;
  let res = await api.selAgentService(form.value.merId);
  salesmanList.value = res.data;
};
/** 提交按钮 */
const submitForm = () => {
  userFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      let res = await api.merchantProductSyd(form.value);
      proxy?.$modal.msgSuccess(res.msg);
      visible.value = false;
      await getList();
    }
  });
};
/**
 * 关闭服务商弹窗
 */
const closeDialog = () => {
  visible.value = false;
  resetForm();
};
/**
 * 重置表单
 */
const resetForm = () => {
  userFormRef.value?.resetFields();
  userFormRef.value?.clearValidate();
};



watch(()=>productList,(val)=>{
  productList.value.forEach(e=>{
      console.log(e);
      if (e.proStatus == 1 && !e.serviceCharge) {
        e.errorClass = 'error-message'
      }else{
        e.errorClass="";
      }
  })
}, { deep: true })




onMounted(async () => {
  await getSelBusType(); // 初始化列表数据
});
</script>

<style lang="scss" scoped>
:deep(.serviceName) {
  .caret-wrapper {
    position: absolute;
    top: 50%;
    transform: translateY(-50%);
    left: 76px;
  }
}
.thHeader {
  .el-icon {
    width: 30px;
    height: 20px;
  }
}
.popover_box {
  .flex_jbetween_acenter {
    margin-top: 3px;
    .el-button {
      width: 49%;
      margin: 0;
    }
  }
}
.card-footer {
  text-align: center;
}


.input-with-validation {
  position: relative;
  display: inline-block;

}

.error-message {
  border: 1px solid red;
}

</style>
